package com.app.sgd.manager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.validator.Resources;

import com.app.sgd.util.Constants;
import com.app.sgd.util.SessionConstants;
import com.app.sgd.view.vo.MessageVO;

public class SGDDispatchAction extends DispatchAction{
    private ActionForward previousForWard;
    private ActionForward currentForWard;
    private static Logger logger = Logger.getLogger(SGDDispatchAction.class.getName());
    
    public SGDDispatchAction(){
        previousForWard = null;
        currentForWard = null;
    }

    /**
     * @deprecated
     */
    public void showMessages(HttpServletRequest request, String message, String [] parameters, String action, String method){
		MessageVO messageVO = new MessageVO();
		messageVO.setAction(action);
		messageVO.setMethod(method);
		
		request.setAttribute("message",messageVO);
		ActionErrors errors = new ActionErrors();
		errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(message,parameters));
		saveErrors(request, errors);
	}

	public void showMessage(HttpServletRequest req, String message, String [] params, String action, String method, int messageType) {
		MessageVO messageVO = new MessageVO();
		messageVO.setAction(action);
		messageVO.setMethod(method);
		messageVO.setMessage(message);
		if (messageType == Constants.SGD_ERROR_CODE){
			messageVO.setImage("action_stop.png");
		}else{
			messageVO.setImage("icon_accept.png");
		}
//		logger.info("[STD] objeto mensaje: "+messageVO.getMessage());
		req.setAttribute("message",messageVO);
		ActionErrors errors = new ActionErrors();
		errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(message,params));
		saveErrors(req, errors);
	}		

	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
    throws Exception{
	    String message = null;
	    boolean existError = false;
	    String parameter = mapping.getParameter();
	    ActionErrors errors = new ActionErrors();
	    HttpSession session = null;
	    String params[] = (String[])null;
	    session = request.getSession(false);
	    logger.info("[STD]: verificando session = " + session.getAttribute(SessionConstants.SGD_USUARIO_SESION_ACTIVO));
	    if(session == null || session.getAttribute(SessionConstants.SGD_USUARIO_SESION_ACTIVO) == null){
	    	logger.info("Se va a lost session");
	    		return mapping.findForward("global.lostSession");
	    }
	    if(parameter == null){
	        System.out.println("par\341metro es null");
	        message = DispatchAction.messages.getMessage("dispatch.handler", mapping.getPath());
	        logger.error(message);
	        return null;
	    }
	    String name = request.getParameter(parameter);
	    System.out.println("method name->" + name);
	    ActionForward actionForward = null;
	    try{
	        actionForward = dispatchMethod(mapping, form, request, response, name);
	        previousForWard = currentForWard;
	        currentForWard = actionForward;
//	        if(currentForWard != null)
//	            logger.debug("currentForWard->" + currentForWard.getPath());
//	        if(previousForWard != null)
//	            logger.debug("previousForWard->" + previousForWard.getPath());
	    }    
	    catch(Exception e){
	        previousForWard = currentForWard;
	        existError = true;
	        message = e.toString();
	        e.printStackTrace();
	    }
	    finally{
	        if(existError){
	            if(message == null){
	                message = "errors.general";
	                errors.add("org.apache.struts.action.GLOBAL_ERROR", new ActionError(message));
	            } else{
	                String messageResource = Resources.getMessage(request, message);
	                if(messageResource == null || messageResource.trim().equals("")){
	                    System.out.println("messageResource es nullo");
	                    errors.add("org.apache.struts.action.GLOBAL_ERROR", new ActionError("errors.general.Global", message));
	                } else
	                if(params == null)
	                    errors.add("org.apache.struts.action.GLOBAL_ERROR", new ActionError(message));
	                else
	                    errors.add("org.apache.struts.action.GLOBAL_ERROR", new ActionError(message, params));
	            }
	            if(previousForWard == null)
	                actionForward = mapping.findForward("global.error.failure");
	            else
	                actionForward = previousForWard;
	            saveErrors(request, errors);
	        }
	    }
//	    System.out.println("<*>StrutsAction.execute2<*>" + UtilDate.formatDate(new Date(),"dd-H:mm:ss:SSS"));
//	    logger.debug("return actionForward->" + actionForward);
//	    System.out.println("<*>StrutsAction.execute3<*>" + (new SimpleDateFormat("dd-H:mm:ss:SSS")).format(new Date()));
	    return actionForward;
	}

	protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String name)
	    throws Exception{
//	    System.out.println("<*>StrutsAction.dispatchMethod1<*>" + UtilDate.formatDate(new Date(),"dd-H:mm:ss:SSS"));
	    if(name == null)
	        return unspecified(mapping, form, request, response);
	    Method method = null;
	    try
	    {
	        method = getMethod(name);
	    }
	    catch(NoSuchMethodException e)
	    {
	        String message = DispatchAction.messages.getMessage("dispatch.method", mapping.getPath(), name);
	        DispatchAction.log.error(message, e);
	        response.sendError(500, message);
	        return null;
	    }
	    ActionForward forward = null;
	    try
	    {
	        Object args[] = {
	            mapping, form, request, response
	        };
	        forward = (ActionForward)method.invoke(this, args);
	    }
	    catch(ClassCastException e)
	    {
	        String message = DispatchAction.messages.getMessage("dispatch.return", mapping.getPath(), name);
	        DispatchAction.log.error(message, e);
	        response.sendError(500, message);
	        return null;
	    }
	    catch(IllegalAccessException e)
	    {
	        String message = DispatchAction.messages.getMessage("dispatch.error", mapping.getPath(), name);
	        DispatchAction.log.error(message, e);
	        response.sendError(500, message);
	        return null;
	    }
	    catch(InvocationTargetException e)
	    {
	        Throwable t = e.getTargetException();
	        if(t instanceof Exception)
	        {
	            System.out.println("Dispatch t instanceof Exception" + e.getMessage());
	            throw (Exception)t;
	        } else
	        {
	            String message = DispatchAction.messages.getMessage("dispatch.error", mapping.getPath(), name);
	            DispatchAction.log.error(message, e);
	            response.sendError(500, message);
	            return null;
	        }
	    }
	    catch(Exception e)
	    {
	        DispatchAction.log.error("Dispatch method error: ->" + e.getMessage());
	    }
//	    System.out.println("<*>StrutsAction.dispatchMethod2<*>" + (new SimpleDateFormat("dd-H:mm:ss:SSS")).format(new Date()));
	    return forward;
	}
}
